package main

import (
	"HoxignTodo/src"
	"HoxignTodo/src/utils"
	"fmt"
	"github.com/gorilla/mux"
	"net/http"
	"time"
)

func RunTodo() {
	r := mux.NewRouter()
	serveFile(r, "static")
	//serveFile(r, "tmpl")
	//serveFile(r, "layout")

	r.HandleFunc("/", src.Index).Methods("GET")
	r.HandleFunc("/index", src.Index).Methods("GET")
	r.HandleFunc("/incomplete", src.Incomplete).Methods("GET")
	r.HandleFunc("/finished", src.Finished).Methods("GET")
	r.HandleFunc("/trash", src.Trash).Methods("GET")

	task := r.PathPrefix("/task").Subrouter()
	task.HandleFunc("/add", src.TaskAdd).Methods("GET", "POST")
	task.HandleFunc("/check/{taskId}", src.TaskCheck).Methods("GET")
	task.HandleFunc("/delete/{taskId}", src.TaskDelete).Methods("GET")
	task.HandleFunc("/edit/{taskId}", src.TaskEdit).Methods("GET", "POST")
	task.HandleFunc("/restore/{taskId}", src.TaskRestore).Methods("GET")
	task.HandleFunc("/finish/{taskId}", src.TaskFinish).Methods("GET")

	r.NotFoundHandler = src.Handler404{}

	srv := &http.Server{
		Handler:      r,
		Addr:         "127.0.0.1:8000",
		WriteTimeout: 15 * time.Second,
		ReadTimeout:  15 * time.Second,
	}
	fmt.Println("Server starts at http://127.0.0.1:8000")
	utils.Must(srv.ListenAndServe())
}

func serveFile(r *mux.Router, dir string) {
	fs := http.FileServer(http.Dir(dir + "/"))
	fs = http.StripPrefix(fmt.Sprintf("/%s/", dir), fs)
	r.PathPrefix(fmt.Sprintf("/%s/", dir)).Handler(fs)
}
